package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC350 {
    public long startExecuteTime = System.currentTimeMillis();

    //    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
//    Output: [4,9]
    public int[] intersect(int[] arr1, int[] arr2) {
        List<Integer> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < arr1.length; i++) {
            if (map.containsKey(arr1[i])) {
                map.put(arr1[i], map.get(arr1[i]) + 1);
            } else {
                map.put(arr1[i], 1);
            }
        }

        for (int i = 0; i < arr2.length; i++) {
            if (map.containsKey(arr2[i])) {
                res.add(arr2[i]);
                if (map.get(arr2[i]) <= 1) {
                    map.remove(arr2[i]);
                } else {
                    map.put(arr2[i], map.get(arr2[i]) - 1);
                }
            }
        }

        int[] resArray = new int[res.size()];
        int i = 0;
        for (Integer re : res) {
            resArray[i++] = re;
        }

        return resArray;
    }


    public static void main(String[] args) throws Exception {
        LC350 an = new LC350();
        int[] arr1 = {4, 9, 5};
        int[] arr2 = {9, 4, 9, 8, 4};
        System.out.println(an.intersect(arr1, arr2));


        System.out.println("\nanswer total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
